#include "ChatBox.hpp"

ChatBox::ChatBox():Panel(0, 0, 250, 150, Panel::BindBottom){
    
    background.setSize(sf::Vector2f(rect.width, rect.height));
    sf::Color bgColor = sf::Color(5,5,5,175);
    background.setFillColor(bgColor);
    add(&background);
    
    inputSeparator.setSize(sf::Vector2f(rect.width, 1));
    inputSeparator.setFillColor(sf::Color::Black);
    inputSeparator.setPosition(0, 135);
    add(&inputSeparator);

    inputBox.setRect(0, 135, rect.width, 15);
    inputBox.labelText.setCharacterSize(12);
    add(&inputBox);
    
    textPanel = new ScrollPanel(0, 0, rect.width, 135, Panel::Static);
    add(textPanel);
    
    textContainer = new StackPanel(0,0, rect.width, 10, Panel::Static, 2);
    textPanel->add(textContainer);
    
    trap(InterfaceEvent::ReleasedKeyboard);
    
}

bool ChatBox::trapped(InterfaceEvent* event){
    if(event->source == &inputBox && event->type == InterfaceEvent::ReleasedKeyboard){
        if(getTextBox()->lastInput == 13 && getText().length() > 0){
			Packet_ChatMessage message;
			message.client = 255;
			strcpy(message.message, getText().c_str());
			NetworkHandler::getInstance()->addMessage(Message::m_b_ChatMessage, &message);
            clearText();
            //Keyboard never released
            getTextBox()->giveKeyboard();
        }
        return true;
    }else{
        return false;
    }
}

void ChatBox::pushMessage(std::string message){
    Label* addMessage = new Label(12, sf::Color::White, message);
    if(messages.size() > 20){
        textContainer->remove(messages.back());
        delete messages.back();
        messages.pop_back();
    }
    messages.push_front(addMessage);
    addMessage->rect.height = 13;
    textContainer->addBottom(addMessage);
    textPanel->updateScrollView();
    textPanel->setScrollBottom();
    
}

std::string ChatBox::getText(){
    return inputBox.text;
}

void ChatBox::clearText(){
    return inputBox.clear();
}

TextBox* ChatBox::getTextBox(){
    return &inputBox;
}

ChatBox::~ChatBox(){
    for(int i = 0; i < messages.size(); i++){
        textContainer->remove(messages.back());
        delete messages.back();
        messages.pop_back();
    }
    textPanel->remove(textContainer);
    delete textContainer;
    delete textPanel;
}